package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdMapper;
import com.heima.admin.service.AdService;
import com.heima.common.exception.CustomException;
import com.heima.model.common.admin.dtos.DataDto;
import com.heima.model.common.admin.dtos.ResponseAdUser;
import com.heima.model.common.admin.pojos.AdUser;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @Author: WDD
 * @Date: 2022/08/11/10:37
 * @Description:
 */
@Service
public class AdServiceImpl extends ServiceImpl<AdMapper, AdUser> implements AdService {
    @Override
    public ResponseAdUser login(AdUser adUser) {
        AdUser user = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUser.getName()));

        if (user == null) {
//            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            return new ResponseAdUser(
                    null,
                    AppHttpCodeEnum.DATA_NOT_EXIST.getCode(),
                    AppHttpCodeEnum.DATA_NOT_EXIST.getErrorMessage(),
                    null);
        }
        if (!user.getPassword().equals(
                DigestUtils.md5DigestAsHex((adUser.getPassword() + user.getSalt()).getBytes())
        )) {
//            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            return new ResponseAdUser(
                    null,
                    AppHttpCodeEnum.LOGIN_PASSWORD_ERROR.getCode(),
                    AppHttpCodeEnum.LOGIN_PASSWORD_ERROR.getErrorMessage(),
                    null);
        }
        user.setSalt("");
        user.setPassword("");
        return new ResponseAdUser(
                null,
                AppHttpCodeEnum.SUCCESS.getCode(),
                AppHttpCodeEnum.SUCCESS.getErrorMessage(),
                new DataDto(
                        user,
                        AppJwtUtil.getToken(user.getId().longValue())
                )
        );
    }
}
